package org.surelink.radius.middleware.auth;

import org.surelink.radius.constant.Vendors;
import org.surelink.radius.middleware.AuthMiddleware;
import org.surelink.radius.model.User;
import org.tinyradius.attribute.RadiusAttribute;
import org.tinyradius.packet.AccessRequest;
import org.tinyradius.packet.RadiusPacket;

import java.util.List;

public class AuthCiscoMiddleware implements AuthMiddleware
{

    @Override
    public RadiusPacket onAuth(User user, AccessRequest request, RadiusPacket response) throws Exception
    {
        parseAttrs(request);
        return response;
    }


    private void parseAttrs(AccessRequest request){

        List<RadiusAttribute> attrs = request.getVendorAttributes(Vendors.CISCO.value()) ;

        for(RadiusAttribute attr: attrs)
        {
            if (attr.getAttributeValue().startsWith("client-mac-address"))
            {
                String macAddress = attr.getAttributeValue();
                macAddress = macAddress.substring("client-mac-address=".length());
                macAddress = macAddress.replaceAll("\\.", "");
                StringBuffer bf = new StringBuffer();
                bf.append(macAddress.substring(0,2)).append(":");
                bf.append(macAddress.substring(2,4)).append(":");
                bf.append(macAddress.substring(4,6)).append(":");
                bf.append(macAddress.substring(6,8)).append(":");
                bf.append(macAddress.substring(8,10)).append(":");
                bf.append(macAddress.substring(10));

                macAddress =  bf.toString();
                request.setMacAddress(macAddress);
            }
        }

        String nasporiid87 = request.getAttributeValue("NAS-Port-Id");
        int vlanid1 = getVlanId(nasporiid87);
        int vlanid2 = getVlanId2(nasporiid87);

        if(vlanid1>0)
            request.setVlanId1(vlanid1);

        if(vlanid2>0)
            request.setVlanId2(vlanid2);

    }

    private  int getVlanId(String nasPortId87)
    {
        //eth phy_slot/phy_subslot/phy_port:XPI.XCI
        if (nasPortId87 == null)
            return 0;

        String str = nasPortId87.toLowerCase();
        int ind1 = str.indexOf(":");
        if (ind1 == -1)
            return 0;

        String vlanId = "0";
        int ind2 = str.indexOf(".", ind1);
        if (ind2 == -1)
            vlanId = str.substring(ind1+1);
        else
            vlanId = str.substring(ind1+1, ind2);

        return Integer.parseInt(vlanId);
    }

    private int getVlanId2(String nasPortId87)
    {
        if (nasPortId87 == null)
            return 0;

        String str = nasPortId87.toLowerCase();
        int ind1 = str.indexOf(".");
        if (ind1 == -1)
            return 0;

        String vlanId2 = "0";
        int ind2 = str.indexOf(" ", ind1);
        if (ind2 == -1)
            vlanId2 = str.substring(ind1+1);
        else
            vlanId2 = str.substring(ind1+1, ind2);

        return Integer.parseInt(vlanId2);
    }

}
